import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
import datetime
import random

class UserConf(webapp.RequestHandler):
    
    
    # GET /?CLIENTNAME=Google+Earth&LOCATION=-99.64360435710162,39.09376543593692,11001000 HTTP/1.1
    def get(self):
        user = users.get_current_user()
        
        # not yet logged in, can't do much with that
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            
        # Get the spectre corresponding to this user
        spectre = Spectre.all().filter("user =", user).get()
        # if the spectre does not exist create one
        if not spectre:
            # i need to create a random enough unique id for the cookie
            # specify A-Za-z0-9
            charset = ([chr(i) for i in range(65,91)]
                     + [chr(i) for i in range(97,123)]
                     + [chr(i) for i in range(0x30,0x3a)])
            cookie = "".join(random.choice(charset) for i in range(15))
            # create a new spectre, setting default location...don't particularly like that
            spectre = Spectre(user=user,
                          longitude='0',
                          latitude='0',
                          altitude='100',
                          cookie=cookie)
            spectre.put()
        # ok, so now I should at least have a spectre object & a user
        # lets display the configuration page to that user
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, locals()))


class NetworkLink(webapp.RequestHandler):
    
    def get(self):
        
        # extract the username from the request
        cookie = self.request.get("COOKIE")
        #print cookie
        # extract the users current location
        (longitude, latitude, altitude) = self.request.get("LOCATION").split(',')
        
        # get the user's spectre
        spectre = Spectre.all().filter("cookie =", cookie).get()
        # update that spectre with the new location informatin
        spectre.longitude = longitude
        spectre.latitude = latitude
        spectre.altitude = altitude
        # update this spectrew
        spectre.put()
        
        # get all spectres that are less than 5 mins old
        # send to template
        delta = datetime.timedelta(minutes=5)
        timeout = (datetime.datetime.now() - delta)
        spectres = Spectre.all().filter("lastupdate >", timeout)
        
        #self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
        #for testing in firefox
        self.response.headers['Content-Type'] = 'text/xml'
        path = os.path.join(os.path.dirname(__file__), 'people.kml')
        self.response.out.write(template.render(path, locals()))


class TogethearthKML(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        
        # not yet logged in, can't do much with that
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            
        # Get the spectre corresponding to this user
        spectre = Spectre.all().filter("user =", user).get()
        
        if not spectre:
            self.redirect('/')
            
        cookie = spectre.cookie
        self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
        #for testing in firefox
        #self.response.headers['Content-Type'] = 'text/xml'
        path = os.path.join(os.path.dirname(__file__), 'togethearth.kml')
        self.response.out.write(template.render(path, locals()))
    

class Spectre(db.Model):
    user = db.UserProperty()
    longitude = db.StringProperty()
    latitude  = db.StringProperty()
    altitude  = db.StringProperty()
    lastupdate = db.DateTimeProperty(auto_now=True)
    cookie = db.StringProperty()







urls = [
     ('/', UserConf),
     ('/people.kml', NetworkLink),
     ('/togethearth.kml', TogethearthKML),
     ]

def main():
  application = webapp.WSGIApplication(
                                       urls,
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)




if __name__ == "__main__":
  main()